package com.example.demo.netty.client.netty;

import com.example.demo.netty.protocol.coder.data.PacketDecoder;
import com.example.demo.netty.protocol.coder.request.PacketEncoder;
import com.example.demo.netty.server.handler.modBusDataHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author Kevin
 * @date 2020/5/4 16:38
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        Scanner sc = null;
        Channel channel = null;
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) {
//                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new PacketDecoder());
                            ch.pipeline().addLast(new modBusDataHandler());
                            ch.pipeline().addLast(new PacketEncoder());
                        }
                    });

            channel = bootstrap.connect("127.0.0.1", 8000).channel();
            sc = new Scanner(System.in);
            String in;
            do {
                in = sc.next();
                channel.writeAndFlush(in);
            } while (!in.equals("bye"));
        } finally {
            sc.close();
            channel.close();
        }

//        while (true) {
//            channel.writeAndFlush(new Date() + ": hello world!");
//            Thread.sleep(2000);
//        }
    }
}
